import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Input, DatePicker, Row, Col, Select, Button, message } from 'antd';
import React, { useEffect, useState } from 'react';
import { useRequest } from '@umijs/hooks';
import router from 'umi/router';
import styles from './index.less'
import moment from 'moment';
import { useActivate } from 'react-activation';
import { _lostCategory, _customsSupervision, _deliveryDepartment } from '../lostItemInfoManage/components/_data'
import PicUpload from './components/PicUpload'
import ShowPic from './components/ShowPic'
import { addUpdateLostArticlesInfo, lostArticlesDetails, getTuCnameByCity3Code, getImgByRelevance, getPkgAccidentDetail, turnToLost } from './service'


const LostItemForm = props => {
  const { form } = props;

  // 遗失物品基础信息
  const stateStr = sessionStorage.getItem('/lostItemManage/lostItemForm');
  const stateObj = stateStr ? JSON.parse(stateStr) : {};

  // 图片上传弹窗显隐
  const [lostItemPicVisible, handleLostItemPicVisible] = useState(false)
  // 图片管理弹窗显隐
  const [lostItemPicManageVisible, handleLostItemPicManageVisible] = useState(false)
  // 是否有图片
  const [lostItemPic, handleLostItemPicture] = useState({ goodFileList: [], touristFileList: [], paperFileList: [] })
  // 图片数组
  const [lostItemPicArr, handleLostItemPicArr] = useState([])
  // 初始图片数组
  const [originPicArr, handleOriginPicArr] = useState([])

  // 表单格式
  const layout = {
    labelCol: {
      span: 9,
    },
    wrapperCol: {
      span: 13,
    },
  };

  // 获取所有入库人接口
  const { data: getTuCnameByCity3CodeD = [] } = useRequest(getTuCnameByCity3Code);
  // 新增、编辑遗失物品接口
  const { run: addUpdateLostArticlesInfoR } = useRequest(params => addUpdateLostArticlesInfo(params), {
    manual: true,
    onSuccess: (res, params) => {
      if (params[0].lostNumber === '') {
        message.success('新增成功')
      } else {
        message.success('编辑成功')
      }
      router.push('/banksearchSystem/lostItemManage/lostItemInfoManage')
    }
  })
  // 遗失物品详情接口
  const { run: lostArticlesDetailsR } = useRequest(params => lostArticlesDetails(params), {
    manual: true,
    onSuccess: (res) => {
      form.setFieldsValue({
        lostArticlesName: res.lostArticlesName,
        pickPeople: res.pickPeople,
        lostCategory: res.lostCategory,
        customsSupervision: res.customsSupervision,
        pickLocation: res.pickLocation,
        deliveryDepartment: res.deliveryDepartment,
        announce: res.announce,
        flightNumber: res.flightNumber,
        flightDate: moment(res.flightDate),
        domesticForeign: res.domesticForeign,
        putStoragePeople: res.putStoragePeople,
        lostFeature: res.lostFeature,
        remark: res.remark
      })
    }
  })
  // 遗失物品图片接口
  const { run: getImgByRelevanceR } = useRequest(params => getImgByRelevance(params), {
    manual: true,
    onSuccess: (res) => {
      handleOriginPicArr(res)
      handleLostItemPicArr(res)
      let goodFileListData = res.filter(item => {
        return item.oneType === 1
      })

      let touristFileListData = res.filter(item => {
        return item.oneType === 2
      })

      let paperFileListData = res.filter(item => {
        return item.oneType === 3
      })

      handleLostItemPicture({ goodFileList: goodFileListData, touristFileList: touristFileListData, paperFileList: paperFileListData })
    }
  })
  // PC获取事故单详情接口
  const { run: runGetPkgAccidentDetail } = useRequest(params => getPkgAccidentDetail(params), {
    manual: true,
    onSuccess(res) {
      console.log(res, 'PC获取事故单详情');
      let data = res.pkgAccidentDetailInfoVo || {}
      form.setFieldsValue({
        flightNumber: data.flightNo,
        flightDate: data.flightDate ? moment(data.flightDate) : '',
      });
    }
  });
  // 多收转遗失接口
  const { run: runTurnToLost } = useRequest(data => turnToLost(data), {
    manual: true,
    onSuccess: (res, data) => {
      router.push('/banksearchSystem/lostItemManage/lostItemInfoManage')
    }
  })

  // 航班号规则
  const flightNumberValidator = (rule, value, callback) => {
    if (value && value.length !== 5 && value.length !== 6) {
      callback("请输入正确的航班号");
    }
    callback();
  }

  // 航班号格式化
  const formatFlightNo = val => {
    if (!val) {
      return '';
    } else if (val.length < 3 || /^\D/.test(val)) {
      return ''.toUpperCase.call(val);
    } else if (/^\d{2}/.test(val)) {
      return `3U${val}`;
    } else {
      return val;
    }
  };

  // 航班日期禁用
  const disabledDate = (current) => {
    return current && current > moment().endOf('day');
  }

  // 提交
  const submit = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      if (fieldsValue.flightDate && fieldsValue.flightDate.isValid()) fieldsValue.flightDate = moment(fieldsValue.flightDate).format('YYYY-MM-DD')
      if (stateObj.type === 'add') {
        // 多收转遗失
        if (stateObj?.isTurn) {
          runTurnToLost({
            ...fieldsValue,
            lostNumber: '',
            img: lostItemPicArr,
            accidentId: stateObj?.accidentId
          })
        } else {
          addUpdateLostArticlesInfoR({ ...fieldsValue, lostNumber: '', img: lostItemPicArr })
        }
      } else {
        let obj = {};
        // 修改后带有id(原本存在后台)的图片
        let lostItemPicIdArr = lostItemPicArr.filter(item => {
          return item.id
        })
        // 新增加的图片
        let lostItemPicNotIdArr = lostItemPicArr.filter(item => {
          return !item.id
        })
        // 找到被删除图片加上remark:1
        let updateArr = originPicArr.concat(lostItemPicIdArr).filter(function (v, i, arr) {
          if (arr.indexOf(v) === arr.lastIndexOf(v)) {
            v.remark = 1
          }
          return arr
        });
        // 去重
        updateArr = updateArr.reduce(function (item, next) {
          obj[next.id] ? '' : obj[next.id] = true && item.push(next);
          return item;
        }, []);

        addUpdateLostArticlesInfoR({ ...fieldsValue, lostNumber: stateObj.lostNumber, img: [...updateArr, ...lostItemPicNotIdArr] })
      }
    });
  }

  // 取消
  const back = () => {
    router.push('/banksearchSystem/lostItemManage/lostItemInfoManage')
  }


  // 新增图片/改变图片
  const handleImgs = async fields => {
    let img = []
    for (let category in fields) {
      fields[category].forEach(imgInfo => {
        if (stateObj.type === 'edit') {
          imgInfo.relevance = stateObj.lostNumber
        }
        img.push(imgInfo)
      })
    }
    handleLostItemPicture(fields)
    handleLostItemPicArr(img)
    handleLostItemPicVisible(false)
  };

  // 删除图片
  const handleDelImgs = async fields => {
    let img = []
    for (let category in fields) {
      fields[category].forEach(imgInfo => {
        img.push(imgInfo)
      })
    }
    handleLostItemPicture(fields)
    handleLostItemPicArr(img)
    handleLostItemPicManageVisible(false)
  }


  useEffect(() => {
    if (stateObj.type === 'edit') {
      lostArticlesDetailsR({ lostNumber: stateObj.lostNumber })
      getImgByRelevanceR({ relevance: stateObj.lostNumber })
    }
    // 多收转遗失
    if (stateObj?.isTurn) {
      runGetPkgAccidentDetail({
        accidentId: stateObj?.accidentId
      })
    }
  }, [])

  // 缓存
  useActivate(() => {
    if (stateObj.type === 'edit') {
      lostArticlesDetailsR({ lostNumber: stateObj.lostNumber })
      getImgByRelevanceR({ relevance: stateObj.lostNumber })
    } else {
      form.setFieldsValue({
        lostArticlesName: '',
        pickPeople: '',
        lostCategory: '',
        customsSupervision: '',
        pickLocation: '',
        deliveryDepartment: '',
        announce: '',
        flightNumber: '',
        flightDate: moment(),
        domesticForeign: '',
        putStoragePeople: '',
        lostFeature: '',
        remark: ''
      })
    }
    // 多收转遗失
    if (stateObj?.isTurn) {
      runGetPkgAccidentDetail({
        accidentId: stateObj?.accidentId
      })
    }
  })

  return (
    <div className={styles.lostItemForm}>
      <Row>
        <Col span={8}>
          <Form.Item
            {...layout}
            label="遗失物品名称"
          >
            {form.getFieldDecorator('lostArticlesName', {
              rules: [
                {
                  required: true,
                  message: '请输入遗失物品名称'
                }
              ]
            })(<Input placeholder='请输入' maxLength={20} />)}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item
            {...layout}
            label="交接人"
          >
            {form.getFieldDecorator('pickPeople', {
              rules: [
                {
                  required: true,
                  message: '请输入交接人'
                }
              ]
            })(<Input placeholder='请输入' maxLength={20} />)}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item
            {...layout}
            label="遗失物品类型"
          >
            {form.getFieldDecorator('lostCategory', {
              rules: [
                {
                  required: true,
                  message: '请选择遗失物品类型'
                }
              ]
            })(
              <Select>
                {
                  _lostCategory.map(item => (
                    <Select.Option value={item.id} title={item.name}>{item.name}</Select.Option>
                  ))
                }
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item
            {...layout}
            label="是否海关监管"
          >
            {form.getFieldDecorator('customsSupervision')(
              <Select>
                {
                  _customsSupervision.map(item => (
                    <Select.Option value={item.id}>{item.name}</Select.Option>
                  ))
                }
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item
            {...layout}
            label="捡拾地点"
          >
            {form.getFieldDecorator('pickLocation', {
              rules: [
                {
                  required: true,
                  message: '请输入捡拾地点'
                }
              ]
            })(<Input placeholder='请输入' maxLength={100} />)}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item
            {...layout}
            label="交接部门"
          >
            {form.getFieldDecorator('deliveryDepartment', {
              rules: [
                {
                  required: true,
                  message: '请选择交接部门'
                }
              ]
            })(
              <Select>
                {
                  _deliveryDepartment.map(item => (
                    <Select.Option value={item.id}>{item.name}</Select.Option>
                  ))
                }
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item
            {...layout}
            label="是否对外公布"
          >
            {form.getFieldDecorator('announce')(
              <Select>
                <Select.Option value={2}>是</Select.Option>
                <Select.Option value={1}>否</Select.Option>
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item
            {...layout}
            label="航班号"
          >
            {form.getFieldDecorator('flightNumber', {
              rules: [
                {
                  validator: flightNumberValidator,
                }
              ],
              getValueFromEvent: (event) => {
                return event.target.value.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g, '')
              }
            })(<Input placeholder='请输入' maxLength={6} disabled={stateObj.isTurn} onChange={(e) => e.target.value = formatFlightNo(e.target.value)} />)}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item
            {...layout}
            label="航班日期"
          >
            {form.getFieldDecorator('flightDate', {
              initialValue: moment()

            })(<DatePicker disabledDate={disabledDate} disabled={stateObj.isTurn} />)}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item
            {...layout}
            label="国际国内"
          >
            {form.getFieldDecorator('domesticForeign', {
              rules: [
                {
                  required: true,
                  message: '请选择国际国内'
                }
              ]
            })(
              <Select>
                <Select.Option value={1}>国内</Select.Option>
                <Select.Option value={2}>国外</Select.Option>
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item
            {...layout}
            label="入库人"
          >
            {form.getFieldDecorator('putStoragePeople', {
              rules: [
                {
                  required: true,
                  message: '请选择入库人'
                }
              ]
            })(
              <Select>
                {
                  getTuCnameByCity3CodeD.map(item => (
                    <Select.Option value={item}>{item}</Select.Option>
                  ))
                }
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={24}>
          <Form.Item
            labelCol={{
              span: 3,
            }}
            wrapperCol={{
              span: 20,
            }}
            label="遗失物品特征"
          >
            {form.getFieldDecorator('lostFeature')(<Input.TextArea placeholder='请输入' />)}
          </Form.Item>
        </Col>
        <Col span={24}>
          <Form.Item
            labelCol={{
              span: 3,
            }}
            wrapperCol={{
              span: 20,
            }}
            label="备注"
          >
            {form.getFieldDecorator('remark')(<Input.TextArea placeholder='请输入' />)}
          </Form.Item>
        </Col>
        <Col span={20} offset={3}>
          <Button type="primary" onClick={() => {
            if (lostItemPic.goodFileList.length === 0 && lostItemPic.touristFileList.length === 0 && lostItemPic.paperFileList.length === 0) {
              handleLostItemPicVisible(true)
            } else {
              handleLostItemPicManageVisible(true)
            }
          }}>图片管理</Button>
        </Col>
        <Col span={24} style={{ textAlign: 'center', marginTop: '20px' }}>
          <Button type="plain" style={{ marginRight: '20px' }} onClick={() => back()}>取消</Button>
          <Button type="primary" onClick={() => submit()}>提交</Button>
        </Col>
      </Row>
      {
        lostItemPicVisible && <PicUpload
          onSubmit={async value => {
            const success = await handleImgs(value)
          }}
          onCancel={() => handleLostItemPicVisible(false)}
          lostItemPicVisible={lostItemPicVisible}
          lostItemPic={lostItemPic}
        ></PicUpload>
      }
      {
        lostItemPicManageVisible && <ShowPic
          onSubmit={async value => {
            const success = await handleDelImgs(value)
          }}
          toUpload={(value) => {
            handleLostItemPicture(value)
            handleLostItemPicManageVisible(false)
            handleLostItemPicVisible(true)
          }}
          onCancel={() => handleLostItemPicManageVisible(false)}
          lostItemPicManageVisible={lostItemPicManageVisible}
          lostItemPic={lostItemPic}
        ></ShowPic>
      }
    </div>
  );
};

export default Form.create()(LostItemForm);
